package com.wenjie.common.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import com.wenjie.gateway.enums.ClentType;
import com.wenjie.utils.EnvironmentUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class TokenUtil {

    public static String createToken(Long userId, ClentType content) {
        byte[] key = EnvironmentUtils.getStr("jwt.token.secretKey").getBytes();
        JWT jwt = JWT.create();
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.HOUR_OF_DAY, 24 * 3);
        jwt.setPayload("userId", userId);
        jwt.setPayload("content", content.getCode());
        jwt.setPayload(JWTPayload.NOT_BEFORE, now); // 生效时间
        jwt.setPayload(JWTPayload.ISSUED_AT, now); // 签发时间
        jwt.setPayload(JWTPayload.EXPIRES_AT, newTime); // 过期时间
        String sign = jwt.setKey(key).sign();
        return sign;
    }


    /**
     * @Description: TODO 获取token中的AdminUserNum
     * @Param:
     * @Return:
     * @Author: wenjie
     * @Date: 2023/2/2
     */
    public static TokenInfo getTokenInfo() {
        HttpServletRequest request = getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            JWT jwt = JWT.of(token);
            Long id = Long.valueOf(jwt.getPayload("userId").toString());
            Integer type = Integer.valueOf(jwt.getPayload("content").toString());
            return new TokenInfo(ClentType.getBycode(type), id);
        }
        return null;
    }


    /**
     * @Description: TODO 获取到当前请求的Request
     * @Param:
     * @Return:
     * @Author: wenjie
     * @Date: 2023/1/30
     */
    @SneakyThrows
    public static HttpServletRequest getRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            throw new Exception("request获取失败");
        }
    }

    @Data
    @AllArgsConstructor
    public static class TokenInfo {
        private ClentType type;
        private Long id;
    }
}
